package com.twb.netty.server;

import com.twb.netty.handler.HearBeatHandler;
import com.twb.netty.handler.NettyWebSocketHandler;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.codec.http.websocketx.extensions.compression.WebSocketServerCompressionHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.IdleStateHandler;

public class NettyServerInitializer extends ChannelInitializer<SocketChannel> {

	@Override
	protected void initChannel(SocketChannel ch) throws Exception {
		ChannelPipeline pipeline = ch.pipeline();
		
		//针对客户端，如果1分钟之内没有向服务器发送读写心跳，则主动断开
        pipeline.addLast(new IdleStateHandler(40,50,60));
		
		pipeline.addLast(new HearBeatHandler());
		
		// HTTP请求的解码和编码
		pipeline.addLast(new HttpServerCodec());
		
		// 把多个消息转换为一个单一的FullHttpRequest或是FullHttpResponse，
		// 原因是HTTP解码器会在每个HTTP消息中生成多个消息对象HttpRequest/HttpResponse,HttpContent,LastHttpContent
		pipeline.addLast(new HttpObjectAggregator(65536));
		
		// 主要用于处理大数据流，比如一个1G大小的文件如果你直接传输肯定会撑暴jvm内存的; 增加之后就不用考虑这个问题了
		pipeline.addLast(new ChunkedWriteHandler());
		
		// WebSocket数据压缩
		pipeline.addLast(new WebSocketServerCompressionHandler());
		
		// 协议包长度限制
		pipeline.addLast(new WebSocketServerProtocolHandler("/ws", null, true));
		
		ch.pipeline().addLast(new NettyWebSocketHandler());
	}

}
